import plugin from '../../lib/plugins/plugin.js';
import fetch from 'node-fetch';

export class UpdateLog extends plugin {
    constructor() {
        super({
            name: '风云更新日志',
            dsc: '查询风云插件仓库的更新日志',
            event: 'message',
            priority: 500,
            rule: [{
                reg: '^#风云更新日志$',
                fnc: 'getUpdateLog'
            }]
        });
        console.log(' ');
    }

    async getUpdateLog(e) {
        try {
            await e.reply('正在从仓库页面解析更新日志，请稍候...');
            const commitData = await this.fetchCommitsFromWeb();
            if (!commitData || commitData.length === 0) {
                await e.reply('未能解析到更新日志，可能是页面结构已更新或无提交记录。');
                return true;
            }
            const message = this.formatCommitsToMessage(commitData);
            await e.reply(message);
        } catch (error) {
            await e.reply('获取更新日志失败，可能是网络问题或页面无法访问。');
        }
        return true;
    }

    async fetchCommitsFromWeb() {
        const pageUrl = 'https://gitcode.com/fengyunnb_admin/fengyun-plugin/commits';
        const response = await fetch(pageUrl, {
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            },
            timeout: 15000
        });

        if (!response.ok) {
            throw new Error(`请求页面失败，状态码: ${response.status}`);
        }

        const html = await response.text();
        const cheerio = await import('cheerio');
        const $ = cheerio.load(html);
        const commits = [];

        // 解析GitCode/GitLab的提交列表结构
        $('li.commit').each((index, element) => {
            if (index >= 10) return false;

            const $el = $(element);
            const titleLink = $el.find('.commit-title a');
            const title = titleLink.text().trim();
            const commitUrl = titleLink.attr('href') || '';
            const commitId = commitUrl ? commitUrl.split('/').pop() : 'N/A';
            const author = $el.find('.commit-author-link').text().trim() || '未知作者';
            const timeElement = $el.find('.committed-date time');
            const timeStr = timeElement.attr('datetime') || timeElement.text().trim();
            
            commits.push({
                id: commitId,
                title: title,
                committer_name: author,
                committed_date: timeStr,
                message: title
            });
        });

        // 如果上述选择器无效，尝试备用选择器
        if (commits.length === 0) {
            $('.commit-row').each((index, element) => {
                if (index >= 10) return false;
                const $el = $(element);
                const title = $el.find('.commit-title').text().trim();
                const commitId = $el.find('.commit-sha').text().trim() || `N/A-${index}`;
                const author = $el.find('.commit-author-name').text().trim() || '未知作者';
                const timeStr = $el.find('.commit-time').text().trim();
                
                commits.push({
                    id: commitId,
                    title: title,
                    committer_name: author,
                    committed_date: timeStr,
                    message: title
                });
            });
        }

        return commits;
    }

    formatCommitsToMessage(commits) {
        if (!commits || commits.length === 0) return '暂无更新日志。';
        let message = '📦 风云插件 近期更新日志\n========================\n\n';
        commits.forEach((commit, index) => {
            const shortId = commit.id.startsWith('N/A') ? commit.id : (commit.id.substring(0, 7));
            message += `${index + 1}. 【${shortId}】\n`;
            message += `   👤 提交者：${commit.committer_name}\n`;
            message += `   📝 摘要：${commit.title}\n`;
            message += `   ⏰ 时间：${commit.committed_date}\n\n`;
        });
        message += '========================\n';
        message += `💡 共解析到最近 ${commits.length} 条提交记录。\n`;
        message += `🔗 页面地址：https://gitcode.com/fengyunnb_admin/fengyun-plugin/commits`;
        return message;
    }
}